import 'dart:convert';

import 'package:boss/main.dart';
import 'package:boss/textStyle/text_style.dart';

import 'package:boss/ui/widget/button/fixed_bottom_btn.dart';
import 'package:boss/ui/widget/center_title_app_bar.dart';
import 'package:boss/ui/widget/form/base_text_form_field.dart';
import 'package:boss/ui/widget/form/new_base_text_form_field.dart';
import 'package:boss/ui/widget/loading/loading.dart';

import 'package:hi_common/hi_common.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:router/annotation.dart';

@RouterConfig(RechargeEdit.pageName)
class RechargeEdit extends StatefulWidget {
  static const pageName = '/rechargeEditPage';

  @Autowired()
  dynamic data;

  RechargeEdit({
    this.data,
  });

  @override
  MyRechargeEdit createState() => MyRechargeEdit('充值/消费规则设置');
}

class MyRechargeEdit extends BaseState<RechargeEdit> {
  List<dynamic> rechargeRewardListArr = [];

  //增删模块的key 值 不加key diff算法识别不出来对应的
  int itemKey = 0;

  num resumeAmount;
  num giveScore;
  num openCardScore;
  num score;
  num scoreTOCashMax;

  MyRechargeEdit(String pageName) : super(pageName);

  @override
  void initState() {
    super.initState();
    rechargeRewardListArr.add({"rechargeAmount": '', "giveAmount": '', "giveScore": '', "key": -1});

    if (widget.data != null) {
      List<Map> newArr = [];
      var rechargeAwardArr = widget.data["rechargeAward"] == null ? [] : json.decode(widget.data["rechargeAward"]);

      for (var z in rechargeAwardArr) {
        itemKey++;
        newArr.add({
          "rechargeAmount": z["rechargeAmount"] == null
              ? null
              : (z["rechargeAmount"] == ''
                  ? null
                  : (z["rechargeAmount"] is String
                      ? (num.parse(z["rechargeAmount"]) / 100).toStringAsFixed(0)
                      : (z["rechargeAmount"] / 100).toStringAsFixed(2))),
          "giveAmount": z["giveAmount"] == null
              ? null
              : (z["giveAmount"] == ''
                  ? null
                  : (z["giveAmount"] is String ? (num.parse(z["giveAmount"]) / 100).toStringAsFixed(0) : (z["giveAmount"] / 100).toStringAsFixed(2))),
          "giveScore": z["giveScore"] == null ? null : (z["giveScore"] == '' ? null : (z["giveScore"] is String ? num.parse(z["giveScore"]) : z["giveScore"])),
          "key": itemKey,
        });
      }
      if (rechargeAwardArr.length != 0) {
        rechargeRewardListArr = newArr;
      }

      if(widget.data["resumeAward"]!=null) {
        resumeAmount =
        (jsonDecode(widget.data["resumeAward"])["resumeAmount"] == null
            ? null
            : (jsonDecode(widget.data["resumeAward"])["resumeAmount"] == ''
            ? null
            : num.parse(
            ((jsonDecode(widget.data["resumeAward"])["resumeAmount"]) / 100)
                .toStringAsFixed(2))));
        giveScore = (jsonDecode(widget.data["resumeAward"])["giveScore"] == null
            ? null
            : (jsonDecode(widget.data["resumeAward"])["giveScore"] == ''
            ? null
            : (jsonDecode(widget.data["resumeAward"])["giveScore"])));

        openCardScore =
        (jsonDecode(widget.data["resumeAward"])["openCardScore"] == null
            ? null
            : (jsonDecode(widget.data["resumeAward"])["openCardScore"] == ''
            ? null
            : (jsonDecode(widget.data["resumeAward"])["openCardScore"])));
      }
      if ((widget.data["scoreToCash"]) != null) {
        score = (jsonDecode(widget.data["scoreToCash"])["score"] == null
            ? null
            : (jsonDecode(widget.data["scoreToCash"])["score"] == ''
                ? null
                : (jsonDecode(widget.data["scoreToCash"])["score"] == 0 ? null : jsonDecode(widget.data["scoreToCash"])["score"])));

        scoreTOCashMax = (jsonDecode(widget.data["scoreToCash"])["scoreTOCashMax"] == null
            ? null
            : (jsonDecode(widget.data["scoreToCash"])["scoreTOCashMax"] == ''
                ? null
                : (jsonDecode(widget.data["scoreToCash"])["scoreTOCashMax"] == 0 ? null : jsonDecode(widget.data["scoreToCash"])["scoreTOCashMax"])));
      }
    }
    setState(() {});
  }

  jsonDecode(str) {
    return json.decode(str);
  }

  //点击保存
  addMemberRuleFun() async {
    if (resumeAmount != null) {
      if (giveScore == null) {
        toast("消费奖励消费赠送填写不完整");
        return null;
      }
    }
    if (giveScore != null) {
      if (resumeAmount == null) {
        toast("消费奖励消费赠送填写不完整");
        return null;
      }
    }

    //score scoreTOCashMax 必须同步
    if (score == null) {
      if (scoreTOCashMax != null) {
        toast("积分抵现模块填写不完整");
        return null;
      }
    }
    if (scoreTOCashMax == null) {
      if (score != null) {
        toast("积分抵现模块填写不完整");
        return null;
      }
    }

    if (score != null && scoreTOCashMax != null) {
      if (score == 0) {
        toast("积分抵现积分至少大于0");
        return null;
      }

      if (scoreTOCashMax > 100) {
        toast("积分抵限百分比不得超过100");
        return null;
      }
      if (scoreTOCashMax == 0) {
        toast("积分抵限百分比不能为0");
        return null;
      }
    }

    //充值奖励
    List<Map> newRechargeRewardListArr = [];
    for (var z in rechargeRewardListArr) {
      num newRechargeAmount = z["rechargeAmount"] == null
          ? null
          : (z["rechargeAmount"] == ''
              ? null
              : (z["rechargeAmount"] is String
                  ? (num.parse((num.parse(z["rechargeAmount"]) * 100).toStringAsFixed(0)))
                  : (num.parse((z["rechargeAmount"] * 100).toStringAsFixed(0)))));
      num newGiveAmount = z["giveAmount"] == null
          ? null
          : (z["giveAmount"] == ''
              ? null
              : (z["giveAmount"] is String
                  ? (num.parse((num.parse(z["giveAmount"]) * 100).toStringAsFixed(0)))
                  : (num.parse((z["giveAmount"] * 100).toStringAsFixed(0)))));
      num newGiveScore = z["giveScore"] == null
          ? null
          : (z["giveScore"] == ''
              ? null
              : (z["giveScore"] is String ? (num.parse((num.parse(z["giveScore"])).toStringAsFixed(0))) : (num.parse((z["giveScore"]).toStringAsFixed(0)))));
      newRechargeRewardListArr.add({
        "rechargeAmount": newRechargeAmount,
        "giveAmount": newGiveAmount,
        "giveScore": newGiveScore,
      });
    }

    //判断充值奖励
    for (var z in newRechargeRewardListArr) {
      if (newRechargeRewardListArr.length == 1) {
        if (z["rechargeAmount"] == null && z["giveAmount"] == null && z["giveScore"] == null) {
          newRechargeRewardListArr = [];
        } else {
          if (z["rechargeAmount"] == null || z["giveAmount"] == null || z["giveScore"] == null) {
            toast("充值奖励填写不完整");
            return null;
          }
        }
      } else {
        if (z["rechargeAmount"] == null || z["giveAmount"] == null || z["giveScore"] == null) {
          toast("充值奖励填写不完整");
          return null;
        }
      }
    }

    try {
      showLoadingToast();
      var res = await api.addMemberRule({
        'addResumeAwardForm':{
          'resumeAmount': (resumeAmount == null ? null : (resumeAmount == '' ? null : (num.parse((resumeAmount * 100).toStringAsFixed(0))))),
          'giveScore': (giveScore == null ? null : (giveScore == '' ? null : (num.parse((giveScore).toStringAsFixed(0))))),
          'openCardScore': (openCardScore == null ? null : (openCardScore == '' ? null : (num.parse((openCardScore).toStringAsFixed(0))))),
        },
        'addScoreToCashForm':{
          'score': (score == null
              ? null
              : (num.parse((score).toStringAsFixed(0))) == 0
              ? null
              : (num.parse((score).toStringAsFixed(0)))),
          'scoreTOCashMax': (scoreTOCashMax),

        },
        'addRechargeAwardFormList': (newRechargeRewardListArr.length == 0 ? [] : newRechargeRewardListArr),
      });

      if (res.successful()) {
        Future.delayed(Duration(milliseconds: 0), () async {
          hideLoadingToast();
        });
        toast("添加成功");
        Future.delayed(Duration(milliseconds: 300), () async {
          Navigator.pop(context, true);
        });
      } else {
        hideLoadingToast();
        toast(res.msg);
      }
    } catch (e) {
      Future.delayed(Duration(milliseconds: 0), () async {
        hideLoadingToast();
      });
    } finally {}
  }

  //增删的充值奖励模块
  rechargeRewardArr() {
    return Column(
      children: (rechargeRewardListArr ?? [])
          .asMap()
          .keys
          .map((item) => Container(
                key: Key((rechargeRewardListArr[item]["key"]).toString()),
                child: Column(
                  children: <Widget>[
                    Row(
                      children: <Widget>[
                        Container(
                          width: 80.w,
                          child: Text(
                            "规则${item + 1}",
                            style: TextStyleConstant().normal_2_24,
                          ),
                        ),
                        Text(
                          "充",
                          style: TextStyleConstant().normal_1_28,
                        ),
                        Expanded(
                          child: BaseMoneyTextFormField(
                            moneyPattern: true,
                            inputFormatters: [FilteringTextInputFormatter.allow(RegUtil.numberReg)],
                            keyboardType: TextInputType.number,
                            textAlign: TextAlign.center,
                            prefixText: '',
                            isRequired: false,
                            maxLength: 8,
                            hintText: '请输入',
                            initialValue: (rechargeRewardListArr[item]["rechargeAmount"] ?? '').toString(),
                            onChanged: (value) {
                              if (value == '') {
                                rechargeRewardListArr[item]["rechargeAmount"] = null;
                                return null;
                              }

                              rechargeRewardListArr[item]["rechargeAmount"] = value.toString();

                              setState(() {});
//
                            },
                          ),
                        ),
                        Text(
                          "元，赠送",
                          style: TextStyleConstant().normal_1_28,
                        ),
                        Expanded(
                          child: BaseMoneyTextFormField(
                            moneyPattern: true,
                            inputFormatters: [FilteringTextInputFormatter.allow(RegUtil.numberReg)],
                            keyboardType: TextInputType.number,
                            textAlign: TextAlign.center,
                            prefixText: '',
                            isRequired: false,
                            maxLength: 8,
                            hintText: '请输入',
                            initialValue: (rechargeRewardListArr[item]["giveAmount"] ?? '').toString(),
                            onChanged: (value) {
                              if (value == '') {
                                rechargeRewardListArr[item]["giveAmount"] = null;
                                return null;
                              }
                              rechargeRewardListArr[item]["giveAmount"] = value.toString();
                              setState(() {});
                            },
                          ),
                        ),
                        Text(
                          "元，赠送",
                          style: TextStyleConstant().normal_1_28,
                        ),
                        Expanded(
                          child: BaseTextFormField(
                            inputFormatters: [FilteringTextInputFormatter.allow(RegUtil.integerReg)],
                            keyboardType: TextInputType.number,
                            textAlign: TextAlign.center,
                            prefixText: '',
                            isRequired: false,
                            maxLength: 8,
                            hintText: '请输入',
                            initialValue: (rechargeRewardListArr[item]["giveScore"] ?? '').toString(),
                            onChanged: (value) {
                              if (value == '') {
                                rechargeRewardListArr[item]["giveScore"] = null;
                                return null;
                              }
                              rechargeRewardListArr[item]["giveScore"] = value.toString();
                              setState(() {});
                            },
                          ),
                        ),
                        Text(
                          "分",
                          style: TextStyleConstant().normal_1_28,
                        ),
                        rechargeRewardListArr.length != 1
                            ? InkWell(
                                onTap: () {
                                  if (rechargeRewardListArr.length == 1) {
                                    return null;
                                  }
                                  rechargeRewardListArr.removeAt(item);

                                  setState(() {});
                                },
                                child: Material(
                                  color: Colors.white,
                                  child: Icon(
                                    Icons.cancel,
                                    size: 36.w,
                                    color: Color.fromRGBO(204, 204, 204, 1),
                                  ),
                                ),
                              )
                            : Container(),
                      ],
                    ),

//              Container(
//                width:double.infinity,
//                height:1,
//                color:Color.fromRGBO(247,247,247, 1),
//              )
                  ],
                ),
              ))
          .toList(),
    );
  }

  //title
  _Itemtitle(String title) {
    return Container(
      child: Padding(
        padding: EdgeInsets.only(
          top: 26.w,
          bottom: 26.w,
        ),
        child: Text(
          "$title",
          style: TextStyleConstant().normal_1_36,
        ),
      ),
    );
  }

  contentList() {
    return Expanded(
      child: SingleChildScrollView(
        child: Padding(
          padding: EdgeInsets.only(
            left: 28.w,
            right: 28.w,
          ),
          child: Container(
            width: double.infinity,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                _Itemtitle("充值奖励"),
                rechargeRewardArr(),
                Padding(
                  padding: EdgeInsets.only(
                    top: 30.w,
                    bottom: 26.w,
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: <Widget>[
                      InkWell(
                        onTap: () {
                          itemKey = itemKey + 1;

                          rechargeRewardListArr.add({"rechargeAmount": '', "giveAmount": '', "giveScore": '', "key": itemKey});
                          setState(() {});
                        },
                        child: Text(
                          "  +新增  ",
                          style: TextStyleConstant().blue_28,
                        ),
                      ),
                    ],
                  ),
                ),
                _Itemtitle("消费奖励"),
                Row(
                  children: <Widget>[
                    Text(
                      "每消费 ",
                      style: TextStyleConstant().normal_1_28,
                    ),
                    Expanded(
                      child: BaseMoneyTextFormField(
                        moneyPattern: true,
                        inputFormatters: [FilteringTextInputFormatter.allow(RegUtil.numberReg)],
                        keyboardType: TextInputType.number,
                        textAlign: TextAlign.center,
                        prefixText: '',
                        isRequired: false,
                        maxLength: 8,
                        hintText: '请输入',
                        initialValue: resumeAmount == null ? '' : resumeAmount.toString(),
                        onChanged: (value) {
                          resumeAmount = (value == '' ? null : num.parse(value));
                          setState(() {});
                        },
                      ),
                    ),
                    Text(
                      " 元，赠送 ",
                      style: TextStyleConstant().normal_1_28,
                    ),
                    Expanded(
                      child: BaseTextFormField(
                        inputFormatters: [FilteringTextInputFormatter.allow(RegUtil.integerReg)],
                        keyboardType: TextInputType.number,
                        textAlign: TextAlign.center,
                        prefixText: '',
                        isRequired: false,
                        maxLength: 8,
                        hintText: '请输入',
                        initialValue: giveScore == null ? '' : giveScore.toString(),
                        onChanged: (value) {
                          giveScore = (value == '' ? null : int.parse(value));
                          setState(() {});
                        },
                      ),
                    ),
                    Text(
                      "分 ",
                      style: TextStyleConstant().normal_1_28,
                    ),
                  ],
                ),
                Row(
                  children: <Widget>[
                    Expanded(
                      child: BaseTextFormField(
                        inputFormatters: [FilteringTextInputFormatter.allow(RegUtil.integerReg)],
                        keyboardType: TextInputType.number,
                        prefixText: '开卡赠送',
                        isRequired: false,
                        hintText: '请输入',
                        maxLength: 8,
                        initialValue: openCardScore == null ? '' : openCardScore.toString(),
                        onChanged: (value) {
                          openCardScore = (value == '' ? null : int.parse(value));

                          setState(() {});
                        },
                      ),
                    ),
                    Text(
                      " 分 ",
                      style: TextStyleConstant().normal_1_28,
                    ),
                  ],
                ),
                _Itemtitle("积分抵现"),
                Row(
                  children: <Widget>[
                    Expanded(
                      child: BaseTextFormField(
                        inputFormatters: [FilteringTextInputFormatter.allow(RegUtil.integerReg)],
                        keyboardType: TextInputType.number,
                        prefixText: '积分抵扣一元现金',
                        isRequired: false,
                        hintText: '请输入',
                        maxLength: 8,
                        initialValue: score == null ? '' : score.toString(),
                        onChanged: (value) {
                          score = (value == '' ? null : num.parse(value));
                          setState(() {});
                        },
                      ),
                    ),
                    Text(
                      " 分 ",
                      style: TextStyleConstant().normal_1_28,
                    ),
                  ],
                ),
                Row(
                  children: <Widget>[
                    Expanded(
                      child: BaseTextFormField(
                        inputFormatters: [FilteringTextInputFormatter.allow(RegUtil.numberReg)],
                        maxLength: 4,
                        keyboardType: TextInputType.number,
                        prefixText: '积分抵现不超过订单金额的',
                        isRequired: false,
                        hintText: '请输入，最高不超过100',
                        initialValue: scoreTOCashMax == null ? '' : scoreTOCashMax.toString(),
                        onChanged: (value) {
                          scoreTOCashMax = (value == '' ? null : num.parse((num.parse(value)).toStringAsFixed(1)));
                          setState(() {});
                        },
                      ),
                    ),
                    Text(
                      " % ",
                      style: TextStyleConstant().normal_1_28,
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CenterTitleAppBar(
        title: '充值/消费规则设置',
        actions: <Widget>[],
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            contentList(),
            FixedBottomBtn(
              title: "保存",
              onTap: () {
                addMemberRuleFun();
              },
              isShowShadow: false,
            ),
          ],
        ),
      ),
    );
  }
}
